from datetime import timedelta
from typing import Annotated
from fastapi import APIRouter, Depends, status, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
from app.api.deps import CurrentUser, SessionDep
from app.core import security
from app.core.config import settings
from app.core.security import get_password_hash
from app.models import  Token, LoginForm,TokenResponse,UserPublicResponse,PhoneRegisterRequest,PhoneRegisterResponse,PhoneVerificationCodeRequest,PhoneVerificationCodeResponse,UserAuth
from app.core.security import verify_password
from app import services
from app import  models

router = APIRouter()
# 发送手机验证码
@router.post("/token/sendsms", response_model=PhoneVerificationCodeResponse)
async def request_verification_code(request: PhoneVerificationCodeRequest, session: SessionDep):
    return await services.UsersService(db=session,current_user=None).request_verification_code(request)
    
# 手机号注册
@router.post("/token/phoneregister", response_model=PhoneRegisterResponse)
async def register_user_by_phone(request: PhoneRegisterRequest,session: SessionDep):
     return await services.UsersService(db=session,current_user=None).register_user_by_phone(request)

@router.post("/login/access-token")
async def login_access_token(
    session: SessionDep, form_data: models.LoginForm
) -> models.LoginResultResponse:
    """
    OAuth2 compatible token login, get an access token for future requests
    """
    
    fileter_str={}
    fileter_str['account']=form_data.username 
    if form_data.login_type=='PHONE':    
        fileter_str['accountType']=models.AccountType.PHONE    
    elif form_data.login_type=='EMAIL':
        fileter_str['accountType']=models.AccountType.EMAIL
    else:
        pass
    db_user = await services.UsersService(db=session,current_user=None).find_user_with_auth_by(fileter_str)     
    
    if not db_user:
        return models.LoginResultResponse(code=400, msg="不正确的用户名",data=None)        
    if not verify_password(form_data.password, db_user.hashed_password):
        return models.LoginResultResponse(code=400, msg="不正确的密码",data=None)                

    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    token = security.create_access_token(
                subject={"userId":db_user.id, 
                 "account":db_user.account,
                 "accountType":db_user.accountType
              },expires_delta=access_token_expires
            )
    user_dict = db_user.dict()
    # if hasattr(db_user, 'userauths') and db_user.userauths:
    #     approved_auths = [auth.dict() for auth in db_user.userauths if auth.authStatus == models.AuthStatusEnum.APPROVED]
    #     user_dict['auth_info'] = approved_auths
    # else:
    #     user_dict['auth_info'] = []
        
    return models.LoginResultResponse(code=0, msg="登录成功",data={**user_dict,"token":token})  
        
   
    

    


@router.post("/login/test-token")
def test_token(current_user: CurrentUser) -> UserPublicResponse:
    """
    Test access token
    """
    return UserPublicResponse(code=0,msg="成功",data=current_user)


# @router.post("/password-recovery/{email}")
# def recover_password(email: str, session: SessionDep) -> Message:
#     """
#     Password Recovery
#     """
#     pass
#     # user = crud111.get_user_by_email(session=session, email=email)

#     # if not user:
#     #     raise HTTPException(
#     #         status_code=404,
#     #         detail="The user with this email does not exist in the system.",
#     #     )
#     # password_reset_token = generate_password_reset_token(email=email)
#     # email_data = generate_reset_password_email(
#     #     email_to=user.email, email=email, token=password_reset_token
#     # )
#     # send_email(
#     #     email_to=user.email,
#     #     subject=email_data.subject,
#     #     html_content=email_data.html_content,
#     # )
#     # return Message(message="Password recovery email sent")


# @router.post("/reset-password/")
# def reset_password(session: SessionDep, body: NewPassword) -> Message:
#     """
#     Reset password
#     """
#     pass
#     # user_id = verify_password_reset_token(token=body.token)
#     # if not user_id:
#     #     raise HTTPException(status_code=400, detail="Invalid token")
#     # user = crud111.get_user_by_email(session=session, email=email)
#     # if not user:
#     #     raise HTTPException(
#     #         status_code=404,
#     #         detail="The user with this email does not exist in the system.",
#     #     )
#     # elif not user.is_active:
#     #     raise HTTPException(status_code=400, detail="Inactive user")
#     # hashed_password = get_password_hash(password=body.new_password)
#     # user.hashed_password = hashed_password
#     # session.add(user)
#     # session.commit()
#     # return Message(message="Password updated successfully")


# @router.post(
#     "/password-recovery-html-content/{email}",
#     dependencies=[Depends(get_current_active_superuser)],
#     response_class=HTMLResponse,
# )
# def recover_password_html_content(email: str, session: SessionDep) -> Any:
#     """
#     HTML Content for Password Recovery
#     """
#     user = crud111.get_user_by_email(session=session, email=email)

#     if not user:
#         raise HTTPException(
#             status_code=404,
#             detail="The user with this username does not exist in the system.",
#         )
#     password_reset_token = generate_password_reset_token(email=email)
#     email_data = generate_reset_password_email(
#         email_to=user.email, email=email, token=password_reset_token
#     )

#     return HTMLResponse(
#         content=email_data.html_content, headers={"subject:": email_data.subject}
#     )
